package com.luming.tkbatis.basemapper.deletemapper;

import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.MapperException;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.SqlHelper;
import tk.mybatis.mapper.provider.IdsProvider;

import java.util.Set;
/**
 * 
 * @ClassName: IdsProviderDefined
 * @Description: 
 	对IdsProvider 进行扩展使他支持批量逻辑删除  创建IdsProvider的子类
 * @author Luming
 * @date 2021-06-13 10:47:20
 */
public class IdsProviderDefined extends IdsProvider {

    public IdsProviderDefined(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    /**
     * deleteShamByIds就是我们门批量逻辑删除的方法，这个方法其实就是再拼装sql，tk中提供了很多帮助我们拼装sql，
     * 	和参数的类（SqlHelper，EntityHelper），我们可以使用
     */
    public String deleteShamByIds(MappedStatement ms) {
        Class<?> entityClass = this.getEntityClass(ms);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.updateTable(entityClass, this.tableName(entityClass)));
        sql.append("<set> is_deleted='1' </set>");
        Set<EntityColumn> columnList = EntityHelper.getPKColumns(entityClass);
        if (columnList.size() == 1) {
            EntityColumn column = (EntityColumn)columnList.iterator().next();
            sql.append(" where ");
            sql.append(column.getColumn());
            sql.append(" in (${_parameter})");
            return sql.toString();
        } else {
            throw new MapperException("继承 deleteByIds 方法的实体类[" + entityClass.getCanonicalName() + "]中必须只有一个带有 @Id 注解的字段");
        }
    }


}

